<template>
  <div class="time-choose-container">
    <div class="main-layout">
      <el-card class="box-card" shadow="never" v-loading="loading">
        <el-page-header title="返回" :icon="ArrowLeft" @back="goBack">
          <template #content>
            <span class="text-large font-600 mr-3">预约时间</span>
          </template>
        </el-page-header>
      
        <div class="reserve-detail">
          <!-- 咨询师信息区域 -->
          <div class="counselor-info">
            <el-avatar :size="80" :src="'/src/assets/images/avatar.png'" />
            <div class="info-text">
              <h2 class="name">{{ counselorData.name }}</h2>
              <p class="title1">{{ `国家${counselorData.level}级` }} / {{ counselorData.workplace }}</p>
            </div>
          </div>
          <div class="basic-info">
            <h2 class="section-title">
              <span class="title-indicator"></span>
              预约时间
            </h2>
            <!-- 添加分隔线 -->
            <div class="divider"></div>
            <!-- 日期选择区 -->
            <div class="date-tabs">
              <el-button 
                v-for="(date, index) in dates" 
                :key="date.date"
                :class="{ active: index === activeDate }"
                @click="selectDate(index)"
                plain>
                <div class="date-content">
                  <div class="weekday" :class="{ 'active-text': index === activeDate }">
                    {{ date.weekday }}
                  </div>
                  <div class="date" :class="{ 'active-text': index === activeDate }">
                    {{ date.displayDate }}
                  </div>
                </div>
              </el-button>
            </div>

            <!-- 时间段选择区 -->
            <div class="time-slots" v-if="dates[activeDate]">
              <!-- 上午时间段 -->
              <div class="period">
                <h3 class="period-title">上午</h3>
                <div class="slots-grid">
                  <el-button 
                    v-for="slot in getMorningSlots(dates[activeDate].date)"
                    :key="slot.time_id"
                    :class="{ 'is-selected': selectedSlot?.time_id === slot.time_id }"
                    @click="selectTimeSlot(slot)"
                    plain>
                    {{ formatTimeSlot(slot) }}
                  </el-button>
                  <div v-if="getMorningSlots(dates[activeDate].date).length === 0" 
                       class="no-slots">
                    暂无可预约时段
                  </div>
                </div>
              </div>

              <!-- 下午时间段 -->
              <div class="period">
                <h3 class="period-title">下午</h3>
                <div class="slots-grid">
                  <el-button 
                    v-for="slot in getAfternoonSlots(dates[activeDate].date)"
                    :key="slot.time_id"
                    :class="{ 'is-selected': selectedSlot?.time_id === slot.time_id }"
                    @click="selectTimeSlot(slot)"
                    plain>
                    {{ formatTimeSlot(slot) }}
                  </el-button>
                  <div v-if="getAfternoonSlots(dates[activeDate].date).length === 0" 
                       class="no-slots">
                    暂无可预约时段
                  </div>
                </div>
              </div>

              <!-- 预约按钮 -->
              <el-button 
                type="primary" 
                class="reserve-btn" 
                :disabled="!selectedSlot"
                :loading="loading"
                @click="handleReserve">
                {{ loading ? '预约中...' : '预约' }}
              </el-button>
            </div>
          </div>
        </div>
  
      </el-card>
    </div>
    <!-- 添加预约成功弹窗 -->
  <el-dialog
    v-model="dialogVisible"
    title="预约提示"
    width="30%"
    :show-close="false"
    center>
    <div class="success-content">
      <el-icon class="success-icon" color="#67C23A" :size="48">
        <CircleCheckFilled />
      </el-icon>
      <p class="success-text">预约成功！</p>
      <p class="success-info">您已成功预约咨询服务</p>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="confirmReserve">确定</el-button>
      </span>
    </template>
  </el-dialog>
  </div>
</template>
  
  <script setup lang="ts">
  import { ref, onMounted, reactive, onUnmounted } from 'vue'
  import { ArrowLeft, CircleCheckFilled } from '@element-plus/icons-vue'
  import router from '@/router'
  import { ElMessage } from 'element-plus'
  import ScheduleApi from '@/api/schedual'
  import AppointmentApi from '@/api/appointment_info'
  import type { UserCounselorData } from '@/api/counselor/types'
  import type { Schedule } from '@/api/schedual/types'
  import type { AppointmentInfo } from '@/api/appointment_info/types'
  import { useUserInfoStore } from '@/stores/info/userInfoStore'
  
  // 状态管理
  const userInfoStore = useUserInfoStore();
  const userId = userInfoStore.userInfo.user_id;
  const dialogVisible = ref(false)
  const loading = ref(false)
  const counselorData = ref<UserCounselorData>({} as UserCounselorData)
  const scheduleList = ref<Schedule[]>([])
  const activeDate = ref(0)
  const selectedSlot = ref<Schedule | null>(null)
  const dates = reactive<{ date: string; weekday: string; displayDate: string }[]>([])

  // 获取路由参数中的咨询师ID
  const counselorId = router.currentRoute.value.params.id as string

  // 初始化咨询师信息
  const initCounselorData = () => {
    const storedInfo = localStorage.getItem('counselorInfo')
    if (storedInfo) {
      counselorData.value = JSON.parse(storedInfo)
    } else {
      ElMessage.error('未获取到咨询师信息')
      router.go(-1)
    }
  }

  // 获取排班信息
  const getScheduleList = async () => {
    loading.value = true
    try {
      const res = await ScheduleApi.getSchedules({
        user_id: counselorId,
        status: 0,
        is_delete: 0
      })
      if (res.data && Array.isArray(res.data)) {
        scheduleList.value = res.data
        generateDates()
      }
    } catch (error) {
      console.error('获取排班信息失败:', error)
      ElMessage.error('获取排班信息失败')
    } finally {
      loading.value = false
    }
  }

  // 日期格式化函数
  const formatDate = (dateStr: string) => {
    const date = new Date(dateStr)
    return {
      date: `${date.getMonth() + 1}月${date.getDate()}日`,
      weekday: ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][date.getDay()]
    }
  }

  // 添加时间段映射
  const periodMap = {
    1: '8：00-8：50',
    2: '9：00-9：50',
    3: '10：00-10：50',
    4: '11：00-11：50',
    5: '14：00-14：50',
    6: '15：00-15：50',
    7: '16：00-16：50'
  }

  // 修改时间段格式化函数
  const formatTimeSlot = (slot: Schedule) => {
    return periodMap[slot.period as keyof typeof periodMap] || '时间未知'
  }

  // 修改获取时间段函数，区分上午和下午
  const getMorningSlots = (date: string) => {
    return scheduleList.value.filter(s => 
      s.date?.startsWith(date) && 
      s.period && 
      s.period <= 4 && 
      s.status === 0
    )
  }

  const getAfternoonSlots = (date: string) => {
    return scheduleList.value.filter(s => 
      s.date?.startsWith(date) && 
      s.period && 
      s.period > 4 && 
      s.status === 0
    )
  }

  // 生成日期数据
  const generateDates = () => {
    const uniqueDates = [...new Set(scheduleList.value.map(s => s.date))].sort()
    dates.length = 0 // 清空原有数据
    uniqueDates.forEach(date => {
      if (date) {
        const formattedDate = formatDate(date)
        dates.push({
          date: date.split('T')[0], // 保留原始日期用于查询
          weekday: formattedDate.weekday,
          displayDate: formattedDate.date // 显示用的格式化日期
        })
      }
    })
  }

  // 选择日期
  const selectDate = (index: number) => {
    activeDate.value = index
    selectedSlot.value = null
  }

  // 选择时间段
  const selectTimeSlot = (slot: Schedule) => {
    selectedSlot.value = slot
  }

  // 处理预约
  const handleReserve = async () => {
    if (!selectedSlot.value || !counselorData.value.user_id) return
    

    if (!userId) {
      ElMessage.error('请先登录')
      router.push('/login/login')
      return
    }

    const currentTime = new Date().toISOString().replace('T', ' ').substring(0, 19)
    
    const appointmentData: AppointmentInfo = {
      record_id: '',
      client_id: userId,
      counselor_id: counselorData.value.user_id,
      time_id: selectedSlot.value.time_id || '',
      request_time: currentTime,
      remark: '预约咨询'
    }

    try {
      loading.value = true
      const res = await AppointmentApi.createAppointment(appointmentData)
      if (res) {
        dialogVisible.value = true
      } else {
        ElMessage.error('预约失败')
      }
    } catch (error) {
      console.error('预约失败:', error)
      ElMessage.error('预约失败，请稍后重试')
    } finally {
      loading.value = false
    }
  }

  // 确认预约后的处理
  const confirmReserve = () => {
    dialogVisible.value = false
    router.push('/reservePage')  // 跳转到我的预约页面
  }

  // 返回上一页
  const goBack = () => {
    router.go(-1)
  }

  onMounted(() => {
    initCounselorData()
    getScheduleList()
  })

  // 组件卸载时确保清理存储的数据
  onUnmounted(() => {
    localStorage.removeItem('counselorInfo')
  })
  </script>
  
<style scoped>
.main-layout {
  min-height: 100vh;  /* 确保最小高度占满视口 */
  background-color: #f5f7fa;  /* 设置背景色 */
}

.reserve-detail {
    margin-top: 20px;
    margin-left: 20px;
    margin-right: 20px;
}
  
.counselor-info {
    margin-left: 80px;
    display: flex;
    width: 100%;
}
  
  .info-text {
    margin-left: 16px;
  }
  
  .name {
    font-size: 24px;
    margin: 0 0 8px 0;
  }
  
  .title1 {
    color: #666;
    margin: 0;
  }
  
  .stats-section {
    display: flex;
    gap: 40px;
    margin-left: 50px;
  }
  
  .stat-item {
    text-align: left;
    margin-left: 40px;
  }
  
  .stat-value {
    font-size: 24px;
    font-weight: bold;
    color: #409EFF;  /* 蓝色数字 */
    margin-bottom: 4px;
  }
  
  .location {
    color: #409EFF;
  }
  
  .unit {
    font-size: 14px;
    margin-left: 2px;
    color: #606266;
  }
  
  .stat-label {
    font-size: 14px;
    color: #606266;
  }
  
  .action-buttons {
    display: flex;
    gap: 20px;
    margin-top: 20px;
    margin-left: auto;  /* 自动占用左侧空间，使按钮靠右 */
    margin-right: 150px;
  }
  
  .message-btn {
    width: 120px;  /* 设置固定宽度 */
    height: 40px;  /* 设置固定高度 */
    font-size: 16px;  /* 设置字体大小 */
    padding: 12px 24px;  /* 设置内边距 */
  }
  
  .reserve-btn {
    width: 120px;          /* 设置固定宽度 */
    height: 40px;          /* 设置固定高度 */
    font-size: 16px;       /* 设置字体大小 */
    padding: 12px 24px;    /* 设置内边距 */
    background-color: #409EFF;  /* Element Plus 默认蓝色 */
    color: #ffffff;        /* 白色字体 */
    border: none;          /* 移除边框 */
    margin-top: 20px;
    /* 可选的样式增强 */
    transition: all 0.3s;  /* 添加过渡效果 */
    font-weight: 500;      /* 稍微加粗字体 */
  }
  
  /* 鼠标悬停效果 */
  .reserve-btn:hover {
    background-color: #66b1ff;  /* 更浅的蓝色 */
    color: #ffffff;
  }
  
  /* 点击效果 */
  .reserve-btn:active {
    background-color: #3a8ee6;  /* 更深的蓝色 */
    color: #ffffff;
  }
  
  .basic-info {
    margin-top: 30px;
    padding: 20px;
    background: #fff;
    border-radius: 8px;
  }
  
  .section-title {
    display: flex;
    align-items: center;
    font-size: 18px;
    margin-bottom: 24px;
    color: #303133;
    margin-left: 100px;
  }
  
  .title-indicator {
    width: 4px;
    height: 18px;
    background-color: #409EFF;
    margin-right: 8px;
    border-radius: 2px;
  }
  
  .divider {
    height: 2px;
    background-color:  #409EFF;  /* Element Plus 的默认边框颜色 */
    margin: 24px 0;             /* 上下间距 */
    margin-left: 100px;
    margin-right: 80px;     
  }

  .date-tabs {
  display: flex;
  gap: 16px;
  margin-bottom: 24px;
  padding: 0 20px;
  overflow-x: auto;
  -webkit-overflow-scrolling: touch;
  justify-content: center;  /* 水平居中 */
  align-items: center;      /* 垂直居中 */
  width: 100%;             /* 确保占满容器宽度 */
}

  /* 日期按钮样式 */
  .date-tabs .el-button {
    height: auto;
    padding: 12px 10px;
    margin: 0;
    min-width: 100px;
    display: flex;
    justify-content: center;  /* 水平居中 */
    align-items: center;      /* 垂直居中 */
  }

  .date-content {
    display: flex;
    flex-direction: column;
    align-items: center;      /* 内容居中对齐 */
    justify-content: center;  /* 垂直方向居中 */
    width: 100%;             /* 占满按钮宽度 */
    text-align: center;      /* 文本居中 */
  }

  .weekday {
    font-size: 16px;
    color: #606266;
    font-weight: 500;
    line-height: 1.5;        /* 调整行高 */
    width: 100%;             /* 占满容器宽度 */
  }

  .date {
    font-size: 14px;
    color: #909399;
    line-height: 1.5;        /* 调整行高 */
    width: 100%;             /* 占满容器宽度 */
  }

  /* 选中状态文字样式 */
  .active-text {
    color: white !important;
  }

  /* 选中状态按钮样式 */
  .date-tabs .el-button.active {
    background-color: #409EFF;
    color: white;
    border-color: #409EFF;
    transform: translateY(-2px);  /* 添加轻微上浮效果 */
    box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);  /* 添加阴影效果 */
  }

  /* 响应式设计 */
  @media (max-width: 768px) {
    .date-tabs {
    justify-content: flex-start;  /* 小屏幕时左对齐 */
    flex-wrap: nowrap;
  }
    
    .date-tabs .el-button {
      min-width: 90px;  /* 移动端稍微缩小最小宽度 */
      padding: 8px 12px;
    }

    .weekday {
      font-size: 14px;
    }

    .date {
      font-size: 12px;
    }
  }

  /* 隐藏横向滚动条但保持功能 */
  .date-tabs::-webkit-scrollbar {
    display: none;
  }

  .date-tabs {
    -ms-overflow-style: none;
    scrollbar-width: none;
  }

  /* 如果需要整体容器也居中，可以添加父容器样式 */
  .time-slots {
    display: flex;
    flex-direction: column;
    align-items: center;     /* 使子元素水平居中 */
    width: 100%;
  }

  .success-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20px 0;
  }

  .success-icon {
    margin-bottom: 16px;
  }

  .success-text {
    font-size: 20px;
    font-weight: 500;
    color: #67C23A;
    margin-bottom: 8px;
  }

  .success-info {
    font-size: 14px;
    color: #606266;
  }

  .dialog-footer {
    width: 100%;
    display: flex;
    justify-content: center;
  }

  :deep(.el-dialog) {
    border-radius: 8px;
  }

  :deep(.el-dialog__header) {
    margin-right: 0;
    text-align: center;
  }

  :deep(.el-dialog__footer) {
    padding-top: 0;
  }
  
  /* 响应式设计 */
  @media (max-width: 768px) {
    .stats-card {
      padding: 16px;
    }
  
    .name {
      font-size: 20px;
    }
  
    .social-buttons {
      flex-direction: column;
    }
  }
  
  .date-tabs {
    display: flex;
    gap: 16px;
    margin-bottom: 24px;
    padding: 0 20px;  /* 添加左右内边距 */
  }
  
  /* 日期按钮样式 */
  .date-tabs .el-button {
    height: auto;
    padding: 12px 24px;
    margin: 0;
  }
  
  /* 选中状态样式 */
  .date-tabs .el-button.active {
    background-color: #409EFF;
    color: white;
    border-color: #409EFF;
  }
  
  .weekday {
    font-size: 14px;
    color: #606266;
    margin-bottom: 4px;
  }
  
  .date {
    font-size: 16px;
    font-weight: 500;
    color: #303133;
  }
  
  /* 响应式设计 */
  @media (max-width: 768px) {
    .date-tabs {
      flex-wrap: wrap;
      justify-content: center;
    }
    
    .date-tabs .el-button {
      width: calc(50% - 8px);  /* 每行两个按钮 */
    }
  }

  /* 添加容器样式 */
  .time-choose-container {
    width: 100%;
    height: 100%;
  }

  .active {
    color: #409EFF;
    border-color: #409EFF;
  }

  .slots-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
    gap: 12px;
    padding: 16px;
    min-height: 80px; /* 确保有最小高度 */
  }

  .no-slots {
    grid-column: 1 / -1;
    text-align: center;
    color: #909399;
    padding: 20px;
    font-size: 14px;
  }

  /* 选中状态样式 */
  .el-button.is-selected {
    background-color: #409EFF;
    color: white;
    border-color: #409EFF;
  }

  /* 时间段按钮样式 */
  .slots-grid .el-button {
    height: 40px;
    font-size: 14px;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .period {
    width: 100%;
    max-width: 800px;
    margin: 0;
  }

  .period-title {
    font-size: 16px;
    color: #606266;
    margin: 16px 0 8px 16px;
    text-align: left;
  }

  .success-content {
    text-align: center;
    padding: 20px 0;
  }

  .success-text {
    font-size: 20px;
    font-weight: 500;
    color: #67C23A;
    margin: 16px 0 8px;
  }

  .success-info {
    font-size: 14px;
    color: #909399;
  }

  .reserve-btn {
    margin-top: 24px;
    width: 200px;
    display: block;
    margin-left: auto;
    margin-right: auto;
  }
</style>